/*Author: Rony Lahav (ID:043489889)*/

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;


/**
 * This class initializes the peer's TCP ServerSocket to listen to incoming connections.
 * When one is accepted the Incoming TCP session is activated
 */
public class TCPListener implements Runnable {
	int myPort = final_project.mainTCPSoc;
	public ServerSocket listenerSS=null;
	
	public TCPListener(ServerSocket soc){
		listenerSS=soc;
	}
	
	public void run()
	{
		do {
			try	
			{
				if (!final_project.isShutDown()){
					listenerSS.setSoTimeout(1000);
					// Preparing the buffer for receiving a message
					byte[] buffer = new byte[final_project.maxBufferSize];
					Socket newSocket = listenerSS.accept(); // Server waits for new connection request
					long id = final_project.getNewUniqueID();
					SingleTCPIncomingConnection tcpInCon = new SingleTCPIncomingConnection(newSocket, id);
					Thread thread = new Thread(tcpInCon);
					final_project.addThreadToLivingList(id, thread);
					thread.start();
				}
			}
			catch(SocketTimeoutException e1){}
			catch(IOException e2){}
		} while (!final_project.isShutDown()); // while not shut down
		
		if (listenerSS != null && !listenerSS.isClosed()){
			try {
				listenerSS.close();
			} catch (IOException e) {}
		}
	}
}
